from flask import Blueprint, request, jsonify
from database import db
from models import Employee, Department
from datetime import datetime

employee_bp = Blueprint('employee', __name__)

@employee_bp.route('/', methods=['GET'])
def get_employees():
    """获取员工列表，支持分页和筛选"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    department_id = request.args.get('department_id', type=int)
    status = request.args.get('status')
    search = request.args.get('search', '')

    # 构建查询
    query = Employee.query.filter_by(is_deleted=False)

    # 应用筛选条件
    if department_id:
        query = query.filter_by(department_id=department_id)
    if status:
        query = query.filter_by(status=status)
    if search:
        query = query.filter(
            (Employee.name.ilike(f'%{search}%')) |
            (Employee.employee_id.ilike(f'%{search}%'))
        )

    # 执行分页查询
    pagination = query.order_by(Employee.created_at.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )

    employees = pagination.items

    # 获取部门信息，用于填充员工数据
    department_dict = {}
    department_ids = [e.department_id for e in employees]
    departments = Department.query.filter(Department.id.in_(department_ids)).all()
    for dept in departments:
        department_dict[dept.id] = dept.name

    # 构建响应数据
    result = []
    for employee in employees:
        employee_data = employee.to_dict()
        employee_data['department'] = department_dict.get(employee.department_id, '')
        result.append(employee_data)

    return jsonify({
        'employees': result,
        'total': pagination.total,
        'page': page,
        'per_page': per_page,
        'pages': pagination.pages
    }), 200

@employee_bp.route('/<int:employee_id>', methods=['GET'])
def get_employee(employee_id):
    """获取单个员工详情"""
    employee = Employee.query.get_or_404(employee_id)

    if employee.is_deleted:
        return jsonify({'error': 'Employee not found'}), 404

    employee_data = employee.to_dict()
    department = Department.query.get(employee.department_id)
    if department:
        employee_data['department'] = department.name

    return jsonify(employee_data), 200

@employee_bp.route('/', methods=['POST'])
def create_employee():
    """创建新员工"""
    print("Received request to create employee")
    data = request.json
    print(f"Request data: {data}")

    if not data:
        print("No data provided")
        return jsonify({'error': 'No data provided'}), 400

    # 检查必要字段
    required_fields = ['employee_id', 'name', 'department_id', 'position', 'phone']
    for field in required_fields:
        if field not in data:
            return jsonify({'error': f'Missing required field: {field}'}), 400

    # 检查工号是否已存在
    existing_employee = Employee.query.filter_by(employee_id=data['employee_id']).first()
    if existing_employee and not existing_employee.is_deleted:
        return jsonify({'error': 'Employee ID already exists'}), 409

    # 检查部门是否存在
    department = Department.query.get(data['department_id'])
    if not department:
        return jsonify({'error': 'Department not found'}), 404

    # 创建新员工
    employee = Employee(
        employee_id=data['employee_id'],
        name=data['name'],
        department_id=data['department_id'],
        position=data['position'],
        phone=data['phone'],
        email=data.get('email'),
        description=data.get('description'),
        status=data.get('status', 'active')
    )

    db.session.add(employee)
    db.session.commit()

    return jsonify({
        'message': 'Employee created successfully',
        'employee': employee.to_dict()
    }), 201

@employee_bp.route('/<int:employee_id>', methods=['PUT'])
def update_employee(employee_id):
    """更新员工信息"""
    employee = Employee.query.get_or_404(employee_id)

    if employee.is_deleted:
        return jsonify({'error': 'Employee not found'}), 404

    data = request.json

    if not data:
        return jsonify({'error': 'No data provided'}), 400

    # 检查部门是否存在
    if 'department_id' in data:
        department = Department.query.get(data['department_id'])
        if not department:
            return jsonify({'error': 'Department not found'}), 404

    # 更新员工信息
    if 'name' in data:
        employee.name = data['name']
    if 'department_id' in data:
        employee.department_id = data['department_id']
    if 'position' in data:
        employee.position = data['position']
    if 'phone' in data:
        employee.phone = data['phone']
    if 'email' in data:
        employee.email = data['email']
    if 'description' in data:
        employee.description = data['description']
    if 'status' in data:
        employee.status = data['status']

    employee.updated_at = datetime.utcnow()
    db.session.commit()

    return jsonify({
        'message': 'Employee updated successfully',
        'employee': employee.to_dict()
    }), 200

@employee_bp.route('/<int:employee_id>', methods=['DELETE'])
def delete_employee(employee_id):
    """删除员工（软删除）"""
    employee = Employee.query.get_or_404(employee_id)

    if employee.is_deleted:
        return jsonify({'error': 'Employee not found'}), 404

    employee.is_deleted = True
    employee.updated_at = datetime.utcnow()
    db.session.commit()

    return jsonify({
        'message': 'Employee deleted successfully'
    }), 200

@employee_bp.route('/departments', methods=['GET'])
def get_departments():
    """获取部门列表"""
    print("Received request to get departments")
    departments = Department.query.filter_by(is_deleted=False).all()

    # 转换为字典列表
    dept_list = [dept.to_dict() for dept in departments]
    print(f"Found {len(dept_list)} departments: {dept_list}")

    return jsonify({
        'departments': dept_list
    }), 200

@employee_bp.route('/departments', methods=['POST'])
def create_department():
    """创建新部门"""
    data = request.json

    if not data or 'name' not in data:
        return jsonify({'error': 'Department name is required'}), 400

    # 检查部门名称是否已存在
    existing_department = Department.query.filter_by(name=data['name']).first()
    if existing_department and not existing_department.is_deleted:
        return jsonify({'error': 'Department name already exists'}), 409

    # 创建新部门
    department = Department(
        name=data['name'],
        description=data.get('description')
    )

    db.session.add(department)
    db.session.commit()

    return jsonify({
        'message': 'Department created successfully',
        'department': department.to_dict()
    }), 201

@employee_bp.route('/departments/<int:department_id>', methods=['PUT'])
def update_department(department_id):
    """更新部门信息"""
    department = Department.query.get_or_404(department_id)

    if department.is_deleted:
        return jsonify({'error': 'Department not found'}), 404

    data = request.json

    if not data:
        return jsonify({'error': 'No data provided'}), 400

    # 检查部门名称是否已存在
    if 'name' in data and data['name'] != department.name:
        existing_department = Department.query.filter_by(name=data['name']).first()
        if existing_department and not existing_department.is_deleted:
            return jsonify({'error': 'Department name already exists'}), 409

    # 更新部门信息
    if 'name' in data:
        department.name = data['name']
    if 'description' in data:
        department.description = data['description']

    department.updated_at = datetime.utcnow()
    db.session.commit()

    return jsonify({
        'message': 'Department updated successfully',
        'department': department.to_dict()
    }), 200

@employee_bp.route('/departments/<int:department_id>', methods=['DELETE'])
def delete_department(department_id):
    """删除部门（软删除）"""
    department = Department.query.get_or_404(department_id)

    if department.is_deleted:
        return jsonify({'error': 'Department not found'}), 404

    # 检查是否有员工属于该部门
    employees_count = Employee.query.filter_by(department_id=department_id, is_deleted=False).count()
    if employees_count > 0:
        return jsonify({'error': f'Cannot delete department with {employees_count} employees'}), 400

    department.is_deleted = True
    department.updated_at = datetime.utcnow()
    db.session.commit()

    return jsonify({
        'message': 'Department deleted successfully'
    }), 200
